# conding:utf-8

from django.shortcuts import render
from django.views.generic.base import View
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

import hashlib

# Create your views here.


class WeChat(View):
    # 使用 @ csrf_exempt是单独为这个函数去掉防止跨站请求伪造功能
    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(WeChat, self).dispatch(*args, **kwargs)

    def get(self, request):
        # 接收微信服务器发送来的参数
        signature = request.GET.get('signature', None)
        timestamp = request.GET.get('timestamp', None)
        nonce = request.GET.get('nonce', None)
        echostr = request.GET.get('echostr', None)

        # 定义token
        token = 'wechatofmyblog'

        # 将token, timestamp, nonce放在列表中，并按字符排序
        hashlist = [token, timestamp, nonce]
        hashlist.sort()
        hashstr = ''.join(hashlist)

        #使用sha1加密
        hashstr = hashlib.sha1(hashstr.encode('utf-8')).hexdigest()

        # 生成的字符串和微信服务器发送过来的字符串比较，如果相同，就把微信服务器发过来的echostr字符串返回去
        if hashstr == signature:
            return HttpResponse(echostr)
